package com.cz.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cz.R;
import com.cz.czchat.LoginActivity;
import com.cz.czchat.TabActivity;
import com.cz.parse.ParseManager;
import com.cz.widget.DemoHelper;
import com.cz.widget.ProgramDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;

import java.io.ByteArrayOutputStream;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link MySpaceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MySpaceFragment extends Fragment implements View.OnClickListener {
    private static final int REQUESTCODE_PICK = 1;
    private static final int REQUESTCODE_CUTTING = 2;
    private ImageView headAvatar;
    private ImageView headPhotoUpdate;
    private ImageView iconRightArrow;
    private TextView tvNickName;
    private TextView tvUsername;
    private RelativeLayout rlNickName;

    private Button logoutBtn;
    private ProgramDialog programDialog;
    private String username = "";
    public MySpaceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MySpaceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MySpaceFragment newInstance(String param1, String param2) {
        MySpaceFragment fragment = new MySpaceFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();

        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });

        programDialog = new ProgramDialog(getActivity());
        initListener();

    }

    private void initView() {
        logoutBtn = getView().findViewById(R.id.btn_login_out);
        headAvatar = (ImageView) getView().findViewById(R.id.user_head_avatar);
        headPhotoUpdate = (ImageView) getView().findViewById(R.id.user_head_headphoto_update);
        tvUsername = (TextView) getView().findViewById(R.id.user_username);
        tvNickName = (TextView) getView().findViewById(R.id.user_nickname);
        rlNickName = (RelativeLayout) getView().findViewById(R.id.rl_nickname);
        iconRightArrow = (ImageView) getView().findViewById(R.id.ic_right_arrow);
    }

    private void initListener() {
        headPhotoUpdate.setVisibility(View.VISIBLE);
        iconRightArrow.setVisibility(View.VISIBLE);
        rlNickName.setOnClickListener(this);
        headAvatar.setOnClickListener(this);
        username = EMClient.getInstance().getCurrentUser();
        if(username != null){
            tvUsername.setText(EMClient.getInstance().getCurrentUser());
            EaseUserUtils.setUserNick(username, tvNickName);
            EaseUserUtils.setUserAvatar(getActivity(), username, headAvatar);
        }
    }
    public void asyncFetchUserInfo(String username){
        DemoHelper.getInstance().getUserProfileManager().asyncGetUserInfo(username, new EMValueCallBack<EaseUser>() {

            @Override
            public void onSuccess(EaseUser user) {
                if (user != null) {
                    DemoHelper.getInstance().saveContact(user);
                    if(getActivity().isFinishing()){
                        return;
                    }
                    tvNickName.setText(user.getNickname());
                    if(!TextUtils.isEmpty(user.getAvatar())){
                        Glide.with(getActivity()).load(user.getAvatar())
                                .apply(RequestOptions.placeholderOf(R.drawable.em_default_avatar))
                                .into(headAvatar);
                    }else{
                        Glide.with(getActivity()).load(R.drawable.em_default_avatar).into(headAvatar);
                    }
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
            }
        });
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_space, container, false);
       // logoutBtn = view.findViewById(R.id.btn_login_out);
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void logout(){
        programDialog.show();
        programDialog.setTextViewValue("正在退出");
        DemoHelper.getInstance().logout(true,new EMCallBack() {

            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        programDialog.dismiss();
                        // show login screen
                        ((TabActivity) getActivity()).finish();
                        startActivity(new Intent(getActivity(), LoginActivity.class));

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        programDialog.dismiss();
                        Toast.makeText(getActivity(), "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_head_avatar:
                Intent pickIntent = new Intent(Intent.ACTION_PICK,null);
                pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(pickIntent, REQUESTCODE_PICK);
                break;
            case R.id.rl_nickname:
                final EditText editText = new EditText(getActivity());
                new AlertDialog.Builder(getActivity()).setTitle(R.string.setting_nickname).setIcon(android.R.drawable.ic_dialog_info).setView(editText)
                        .setPositiveButton(R.string.dl_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String nickString = editText.getText().toString();
                                if (TextUtils.isEmpty(nickString)) {
                                    Toast.makeText(getActivity(), getString(R.string.toast_nick_not_isnull), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                updateRemoteNick(nickString);
                            }
                        }).setNegativeButton(R.string.dl_cancel, null).show();
                break;
            default:
                break;
        }
    }

    private void updateRemoteNick(final String nickName) {
        programDialog.show();
        programDialog.setTextViewValue("正在修改...");
        new Thread(new Runnable() {

            @Override
            public void run() {
                boolean updatenick = DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(nickName);
                if (getActivity().isFinishing()) {
                    return;
                }
                if (!updatenick) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getActivity(), getString(R.string.toast_updatenick_fail), Toast.LENGTH_SHORT)
                                    .show();
                            programDialog.dismiss();
                        }
                    });
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            programDialog.dismiss();
                            Toast.makeText(getActivity(), getString(R.string.toast_updatenick_success), Toast.LENGTH_SHORT)
                                    .show();
                            tvNickName.setText(nickName);
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case REQUESTCODE_PICK:
                if (data == null || data.getData() == null) {
                    return;
                }
                startPhotoZoom(data.getData());
                break;
            case REQUESTCODE_CUTTING:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    /**
     * save the picture data
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(getResources(), photo);
            headAvatar.setImageDrawable(drawable);
            uploadUserAvatar(Bitmap2Bytes(photo));
        }

    }

    private void uploadUserAvatar(final byte[] data) {
        programDialog.show();
        programDialog.setTextViewValue("正在上传...");
        new Thread(new Runnable() {

            @Override
            public void run() {

//                Log.i("TAG", "上传头香");
//                ParseFile pFile = new ParseFile(data);
//                ParseObject pUser = null;
//                pUser =new ParseObject("czchat");
//                pUser.put("avatar", pFile);
//                Log.i("TAG", "uploadParseAvatar: "+pFile.getUrl());
//                try {
//                    pUser.save();
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }

                final String avatarUrl = DemoHelper.getInstance().getUserProfileManager().uploadUserAvatar(data);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        programDialog.dismiss();
                        if (avatarUrl != null) {
                            Toast.makeText(getActivity(), getString(R.string.toast_updatephoto_success),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), getString(R.string.toast_updatephoto_fail),
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }
        }).start();

    }


    public byte[] Bitmap2Bytes(Bitmap bm){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
}
